package com.cloudsea.yunhaistores.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cloudsea.yunhaistores.dto.SpuAddDTO;
import com.cloudsea.yunhaistores.dto.SpuUpdateDTO;
import com.cloudsea.yunhaistores.entity.Spus;
import com.cloudsea.yunhaistores.service.SpuService;
import com.cloudsea.yunhaistores.vo.SpuDetailVO;
import com.cloudsea.yunhaiutils.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "商家-商品(SPU)管理", description = "商家用于管理后台商品的接口")
@RestController
@RequestMapping("/spus")
public class SpuController {

    @Autowired
    private SpuService spuService;

    @Operation(summary = "新增商品", description = "创建一个包含至少一个规格(SKU)的完整商品")
    @PostMapping("/add")
    public ApiResponse<Spus> addSpu(@Valid @RequestBody SpuAddDTO dto) {
        Spus newSpu = spuService.addSpu(dto);
        return ApiResponse.success("商品添加成功", newSpu);
    }

    @Operation(summary = "查询商品详情", description = "根据SPU ID获取商品的详细信息，包括其下所有SKU")
    @GetMapping("/select/{spuId}")
    public ApiResponse<SpuDetailVO> getSpuDetail(@PathVariable Long spuId) {
        return ApiResponse.success(spuService.getSpuDetailById(spuId));
    }

    @Operation(summary = "修改商品信息", description = "更新SPU的基本信息，如名称、分类、状态等")
    @GetMapping("/updata/{spuId}")
    public ApiResponse<Void> updateSpu(@PathVariable Long spuId, @RequestBody SpuUpdateDTO dto) {
        spuService.updateSpu(spuId, dto);
        return ApiResponse.success("商品更新成功", null);
    }

    @Operation(summary = "分页查询商品列表", description = "根据门店ID分页获取商品列表，可根据关键词搜索")
    @GetMapping("/list")
    public ApiResponse<IPage<Spus>> listSpus(
            @Parameter(description = "门店ID", required = true) @RequestParam Long storeId,
            @Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", required = true) @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "搜索关键词(商品名)") @RequestParam(required = false) String keyword
    ) {
        IPage<Spus> page = spuService.listSpusByPage(storeId, pageNum, pageSize, keyword);
        return ApiResponse.success(page);
    }

    @Operation(summary = "删除商品", description = "删除一个SPU及其下所有关联的SKU")
    @GetMapping("/delete/{spuId}")
    public ApiResponse<Void> deleteSpu(@PathVariable Long spuId) {
        spuService.deleteSpu(spuId);
        return ApiResponse.success("商品删除成功", null);
    }
}
